<template>
  <div class="home-container">
  <!-- 头部导航 -->
  <div class="header">
    <div class="header-inner">
      <div class="logo">
        <img src="@/assets/Logo.png" alt="鲸选Logo" />
      </div>
      <div class="search-bar" @click.stop>
        <input v-model="searchQuery" type="text" placeholder="搜索" @focus="showHistoryDropdown = true"
          @keypress.enter="handleSearch" />
        <div v-show="showHistoryDropdown" class="search-history-dropdown">
          <template v-if="searchHistory.length > 0">
            <div v-for="(term, index) in searchHistory" :key="index" class="search-history-item"
              @click="selectHistory(term)">
              {{ term }}
            </div>
            <div class="search-history-item"
              style="color: #000; text-align: center; border-top: 1px solid #eee; margin-top: 8px;"
              @click="clearSearchHistory">
              🗑️ 清空历史记录
            </div>
          </template>
          <div v-else class="search-history-item" style="padding: 10px; text-align: center; color: #999;">
            暂无搜索记录
          </div>
        </div>
        <button @click="handleSearch">搜索</button>
      </div>

      <!-- 用户信息区域 -->
      <div class="user-info" @click.stop>
        <div class="user-avatar">
          <img :src="userAvatar" alt="用户头像" />
        </div>
        <div>
          <span class="username" @click="toggleDropdown">
            {{ displayName }}
          </span>
          <div v-show="isDropdownOpen" class="dropdown-menu">
            <div v-for="(item, index) in dropdownItems" :key="index" class="dropdown-item"
              @click="handleDropdownClick(item)">
              {{ item.text }}
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- 主体内容 -->
  <div class="main-content">
    <!-- 左侧分类 -->
    <div class="sidebar">
      <div v-for="category in categories" :key="category.name" class="sidebar-item"
        @mouseenter="hoveredCategory = category.name" @mouseleave="hoveredCategory = null">
        <span>
          {{ category.name }}
        </span>

        <!-- 悬浮子分类菜单 -->
        <div v-if="category.sub.length > 0" v-show="hoveredCategory === category.name" class="sub-category">
          <div v-for="sub in category.sub" :key="sub" class="sub-item" @click="goToSearch(sub)">
            {{ sub }}
          </div>
        </div>
      </div>
    </div>

    <!-- 中间推荐商品 -->
    <div class="main-banner">
      <div class="carousel-container">
        <div class="carousel-slides" :style="{ transform: `translateX(-${currentIndex * 100}%)` }">
          <div v-for="(slide, index) in carouselItems" :key="slide.productId || index" class="slide"
            @click="handleSlideClick(slide)" @keyup.enter.prevent="handleSlideClick(slide)" role="button" tabindex="0">
            <img :src="slide.imageUrl || defaultProductImage" :alt="slide.productName" />
            <div class="slide-info">
              <div class="slide-text">
                <h3 class="slide-title">{{ slide.productName }}</h3>
                <p v-if="slide.description" class="slide-subtitle">{{ slide.description }}</p>
              </div>
              <p class="slide-price">{{ displayPrice(slide.price) }}</p>
            </div>
          </div>
        </div>

        <button class="carousel-arrow left" @click="prevSlide">❮</button>
        <button class="carousel-arrow right" @click="nextSlide">❯</button>

        <div class="carousel-indicators">
          <span v-for="(indicator, index) in carouselItems" :key="indicator.productId || index" class="indicator"
            :class="{ active: currentIndex === index }" @click="goToSlide(index)"></span>
        </div>
      </div>
    </div>

    <!-- 右侧榜单入口 -->
    <div class="rankings-entry">
      <div class="ranking-card hot-sale" @click="goToRanking('recommend')">
        <div class="card-icon">🔥</div>
        <div class="card-title">月热销榜</div>
        <div class="card-desc">大家都在买</div>
      </div>
      <div class="ranking-card good-reputation" @click="goToRanking('new-product')">
        <div class="card-icon">👍</div>
        <div class="card-title">好评榜</div>
        <div class="card-desc">千万好评</div>
      </div>
      <div class="ranking-card good-price" @click="goToRanking('value')">
        <div class="card-icon">💰</div>
        <div class="card-title">好价榜</div>
        <div class="card-desc">超值低价</div>
      </div>
    </div>
  </div>

  <!-- 商品展示区 -->
  <div class="product-grid">
    <div v-if="loading" class="loading-container">
      <p>正在加载推荐商品...</p>
    </div>
    <div v-else-if="error" class="error-container">
      <p>{{ error }}</p>
      <button @click="loadRecommendProducts">重新加载</button>
    </div>
    <template v-else>
      <router-link v-for="product in products" :key="product.productId" :to="`/iteminfo/${product.productId}`"
        class="product-card-link">
        <div class="product-card" @click="viewProduct(product)">
          <div class="product-image">
            <img :src="product.imageUrl || defaultProductImage" :alt="product.productName" />
          </div>
          <div class="product-info">
            <h3 class="product-title">{{ product.productName || '商品名称' }}</h3>
            <div v-if="product.platformName" class="product-subtitle">{{ product.platformName }}</div>
            <!-- 新增：商品描述 -->
            <div class="product-description">
              {{ product.description || '暂无描述' }}
            </div>
            <!-- 新增：第一个用户评价 -->
            <div v-if="product.reviews && product.reviews[0]" class="user-review">
              <strong>用户评价:</strong>
              {{ product.reviews[0] }}
            </div>
            <div class="product-price">{{ displayPrice(product.price) }}</div>
          </div>
        </div>
      </router-link>
    </template>
  </div>
  </div>

</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount, watch } from 'vue'
import { useRouter } from 'vue-router'
import {
  getRecommendProducts,
  recordBrowseBehavior,
  recordSearchBehavior,
  logout as logoutApi,
  getCurrentUser
} from '@/api'
import { useUserStore } from '@/stores/user'
import { products as staticProducts } from '@/stores/product.js'

const router = useRouter()
const userStore = useUserStore()

// ========== 分类数据 ==========
const categories = [
  { name: '手机/数码', sub: ['智能手机', '平板电脑', '耳机', '相机'] },
  { name: '电脑/办公', sub: ['笔记本', '台式机', '显示器', '打印机'] },
  { name: '男装/女装/童装', sub: ['T恤', '衬衫', '连衣裙', '童装'] },
  { name: '家具/家居', sub: ['沙发', '床', '灯具', '收纳'] },
  { name: '家用电器', sub: ['冰箱', '洗衣机', '空调', '电视'] },
  { name: '母婴/玩具', sub: ['奶粉', '湿巾', '玩具'] },
  { name: '美妆/个护', sub: ['口红', '面膜', '粉底'] }
]
const hoveredCategory = ref(null)

// ========== 推荐商品常量 ==========
const CAROUSEL_MAX_ITEMS = 5
const MIN_GRID_ITEMS = 4
const DESIRED_MIN_ITEMS = CAROUSEL_MAX_ITEMS + MIN_GRID_ITEMS
const DEFAULT_IMAGE = 'https://via.placeholder.com/400x400?text=商品图片'

const normalizeProduct = (raw, index = 0) => {
  if (!raw) return null
  const productId = raw.productId ?? raw.id ?? raw.productID ?? raw.ID
  if (productId === undefined || productId === null || productId === '') {
    return null
  }
  const priceNumber = Number(raw.price)
  return {
    productId: String(productId),
    productName: raw.productName || raw.title || `推荐商品${index + 1}`,
    imageUrl: raw.imageUrl || raw.img || DEFAULT_IMAGE,
    price: Number.isFinite(priceNumber) ? priceNumber : raw.price ?? null,
    description: raw.description || '',
    platformName: raw.platformName || raw.platform || '',
    reviews: Array.isArray(raw.reviews) ? raw.reviews : []
  }
}

const fallbackProductPool = staticProducts
  .map((item, index) => normalizeProduct(item, index))
  .filter(Boolean)

const carouselProducts = ref([])
const defaultProductImage = DEFAULT_IMAGE

const carouselItems = computed(() => {
  if (carouselProducts.value.length > 0) {
    return carouselProducts.value
  }
  return fallbackProductPool.slice(0, CAROUSEL_MAX_ITEMS)
})

const carouselTabs = computed(() =>
  carouselItems.value.map((item, index) => item.productName || `推荐商品${index + 1}`)
)
const currentIndex = ref(0)
let autoSlideTimer = null

const goToSlide = (index) => {
  const length = carouselItems.value.length
  if (length === 0) {
    currentIndex.value = 0
    return
  }
  const normalizedIndex = ((index % length) + length) % length
  currentIndex.value = normalizedIndex
}

const nextSlide = () => {
  const length = carouselItems.value.length
  if (length <= 1) {
    currentIndex.value = 0
    return
  }
  currentIndex.value = (currentIndex.value + 1) % length
}

const prevSlide = () => {
  const length = carouselItems.value.length
  if (length <= 1) {
    currentIndex.value = 0
    return
  }
  currentIndex.value = (currentIndex.value - 1 + length) % length
}

const handleSlideClick = async (product) => {
  if (!product?.productId) {
    return
  }
  try {
    await viewProduct(product)
  } finally {
    router.push({ path: `/iteminfo/${product.productId}` })
  }
}

watch(carouselItems, (items) => {
  if (!items || items.length === 0) {
    currentIndex.value = 0
    return
  }
  if (currentIndex.value >= items.length) {
    currentIndex.value = 0
  }
})

// ========== 用户下拉菜单 ==========
const isDropdownOpen = ref(false)
const dropdownItems = [
  { text: '购物车', to: '/shopping-cart' },
  { text: '个人中心', to: '/personalcenter' },
  { text: '个人资料', to: '/personalinfo' },
  { text: '切换账号', to: '/user-login' },
  { text: '修改密码', to: '/change-password' },
  { text: '退出登录', to: '/user-login' }
]

const defaultAvatar = new URL('@/assets/user-01.svg', import.meta.url).href
const userAvatar = computed(() => userStore.info?.icon || defaultAvatar)
const displayName = computed(() => userStore.userName || '未登录')

const toggleDropdown = () => {
  isDropdownOpen.value = !isDropdownOpen.value
}

const handleDropdownClick = async (item) => {
  isDropdownOpen.value = false
  if (item.text === '退出登录') {
    if (confirm('确定要退出登录吗？')) {
      try {
        await logoutApi()
      } catch (error) {
        console.warn('退出登录接口调用失败:', error)
      }
      userStore.clearAuth()
      router.push('/user-login')
    }
    return
  }

  if (item.text === '切换账号') {
    userStore.clearAuth()
    router.push(item.to || '/user-login')
    return
  }

  if (item.to) {
    router.push(item.to)
  }
}

// ========== 搜索历史 ==========
const searchQuery = ref('')
const showHistoryDropdown = ref(false)
const searchHistory = ref([])

const loadSearchHistory = () => {
  try {
    const stored = JSON.parse(localStorage.getItem('searchHistory') || '[]')
    searchHistory.value = Array.isArray(stored) ? stored : []
  } catch (error) {
    console.warn('解析搜索历史失败，已清空', error)
    searchHistory.value = []
    localStorage.removeItem('searchHistory')
  }
}

const saveSearchHistory = (term) => {
  const cleanTerm = term.trim()
  if (!cleanTerm) return
  const history = [cleanTerm, ...searchHistory.value.filter((t) => t !== cleanTerm)].slice(0, 10)
  localStorage.setItem('searchHistory', JSON.stringify(history))
  searchHistory.value = history
}

const clearSearchHistory = () => {
  localStorage.removeItem('searchHistory')
  searchHistory.value = []
  searchQuery.value = ''
}

const formatDateTime = (date = new Date()) => {
  const d = new Date(date)
  const pad = (value) => String(value).padStart(2, '0')
  // 获取时区偏移量（分钟），转换为小时和分钟
  const offset = -d.getTimezoneOffset() // getTimezoneOffset 返回的是 UTC 与本地时间的差值（分钟）
  const offsetHours = Math.floor(Math.abs(offset) / 60)
  const offsetMinutes = Math.abs(offset) % 60
  const offsetSign = offset >= 0 ? '+' : '-'
  const offsetStr = `${offsetSign}${pad(offsetHours)}:${pad(offsetMinutes)}`
  // 返回 ISO 8601 格式，包含时区信息
  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}${offsetStr}`
}
const toNumber = (value) => {
  const num = Number(value)
  return Number.isFinite(num) ? num : undefined
}

const sendSearchBehavior = async (keyword, extra = {}) => {
  if (!userStore.isLoggedIn || !keyword) return
  try {
    await recordSearchBehavior({
      userId: userStore.userId,
      keyword,
      timestamp: formatDateTime(),
      ...extra
    })
  } catch (error) {
    console.warn('记录搜索行为失败:', error)
  }
}

const selectHistory = (term) => {
  const cleanTerm = term.trim()
  if (!cleanTerm) return
  searchQuery.value = cleanTerm
  saveSearchHistory(cleanTerm)
  sendSearchBehavior(cleanTerm)
  showHistoryDropdown.value = false
  router.push({ path: '/search', query: { q: cleanTerm } })
}

const handleSearch = () => {
  const query = searchQuery.value.trim()
  if (!query) return
  saveSearchHistory(query)
  sendSearchBehavior(query)
  showHistoryDropdown.value = false
  router.push({ path: '/search', query: { q: query } })
}

// ========== 商品数据 ==========
const products = ref([])
const loading = ref(false)
const error = ref(null)

const normalizeRecommendList = (payload) => {
  if (!payload) return []
  if (Array.isArray(payload)) return payload
  if (Array.isArray(payload.data)) return payload.data
  if (Array.isArray(payload.records)) return payload.records
  if (Array.isArray(payload.recommendations)) return payload.recommendations
  if (payload.data && Array.isArray(payload.data.records)) return payload.data.records
  if (payload.data && Array.isArray(payload.data.recommendations)) return payload.data.recommendations
  return []
}

const augmentWithFallback = (list) => {
  if (list.length >= DESIRED_MIN_ITEMS || fallbackProductPool.length === 0) {
    return list
  }
  const augmented = [...list]
  const seen = new Set(augmented.map((item) => item.productId))
  for (const fallback of fallbackProductPool) {
    if (augmented.length >= DESIRED_MIN_ITEMS) {
      break
    }
    if (!seen.has(fallback.productId)) {
      augmented.push({ ...fallback })
      seen.add(fallback.productId)
    }
  }
  return augmented
}

const determineCarouselCount = (length) => {
  if (length <= 0) return 0
  if (length <= MIN_GRID_ITEMS) {
    return Math.min(2, length)
  }
  let count = Math.min(CAROUSEL_MAX_ITEMS, length)
  if (length - count < MIN_GRID_ITEMS) {
    count = Math.max(0, length - MIN_GRID_ITEMS)
  }
  return count
}

const applyRecommendationData = (rawList) => {
  const mapped = []
  const seen = new Set()
  rawList.forEach((item, index) => {
    const product = normalizeProduct(item, index)
    if (!product) return
    if (seen.has(product.productId)) return
    seen.add(product.productId)
    mapped.push(product)
  })

  const enriched = augmentWithFallback(mapped)
  if (enriched.length === 0) {
    carouselProducts.value = []
    products.value = []
    return false
  }

  const carouselCount = determineCarouselCount(enriched.length)
  carouselProducts.value = enriched.slice(0, carouselCount)
  const carouselIdSet = new Set(carouselProducts.value.map((item) => item.productId))
  products.value = enriched.filter((item) => !carouselIdSet.has(item.productId))
  return carouselProducts.value.length > 0 || products.value.length > 0
}

const displayPrice = (value) => {
  const num = Number(value)
  if (Number.isFinite(num)) {
    return `¥${num.toFixed(2)}`
  }
  if (value !== null && value !== undefined && value !== '') {
    const text = String(value)
    return text.startsWith('¥') ? text : `¥${text}`
  }
  return '¥0.00'
}

const loadRecommendProducts = async () => {
  loading.value = true
  error.value = null
  try {
    const response = await getRecommendProducts(20)
    const list = normalizeRecommendList(response)
    if (!applyRecommendationData(list)) {
      console.warn('推荐列表为空，使用备用数据')
      if (!applyRecommendationData(staticProducts)) {
        error.value = '暂无推荐商品，请稍后重试'
      }
    }
  } catch (err) {
    console.warn('API获取推荐商品失败，使用静态数据:', err)
    if (!applyRecommendationData(staticProducts)) {
      error.value = '加载推荐商品失败，请稍后重试'
    }
  } finally {
    loading.value = false
  }
}

const ensureUserInfo = async () => {
  if (!userStore.isLoggedIn || userStore.info) {
    return
  }
  try {
    const res = await getCurrentUser()
    if (res?.data) {
      userStore.setUserInfo(res.data)
    }
  } catch (error) {
    console.warn('刷新用户信息失败，即将跳转到登录页', error)
    userStore.clearAuth()
    router.push('/user-login')
  }
}

const viewProduct = async (product) => {
  if (!product?.productId) return
  console.log('查看商品:', product)
  try {
    if (userStore.isLoggedIn) {
      const now = new Date()
      const payload = {
        userId: userStore.userId,
        productId: Number(product.productId),
        startTime: formatDateTime(new Date(now.getTime() - 3000)),
        endTime: formatDateTime(now),
        pageDepth: 1,
        pageCount: 1
      }
      const price = toNumber(product.price)
      if (price !== undefined) {
        payload.price = price
      }
      if (product.platformName) {
        payload.category = product.platformName
      }
      await recordBrowseBehavior(payload)
      console.log('浏览行为已记录')
    }
  } catch (error) {
    console.warn('记录浏览行为失败:', error)
  }
  // TODO: 跳转到商品详情页
  // router.push({ path: '/product', query: { id: product.productId } })
}

const goToSearch = (keyword) => {
  const cleanKeyword = (keyword || '').trim()
  if (!cleanKeyword) return
  sendSearchBehavior(cleanKeyword)
  router.push({ path: '/search', query: { q: cleanKeyword } })
  hoveredCategory.value = null
}

const goToRanking = (type) => {
  router.push({ path: '/rankings', query: { type } })
}

// ========== 统一点击外部关闭 ==========
const handleClickOutside = (e) => {
  if (!e.target.closest('.user-info')) {
    isDropdownOpen.value = false
  }
  if (!e.target.closest('.search-bar')) {
    showHistoryDropdown.value = false
  }
}

onMounted(() => {
  ensureUserInfo()
  loadSearchHistory()
  loadRecommendProducts()
  autoSlideTimer = setInterval(nextSlide, 3000)
  document.addEventListener('click', handleClickOutside)
})

onBeforeUnmount(() => {
  if (autoSlideTimer) clearInterval(autoSlideTimer)
  document.removeEventListener('click', handleClickOutside)
})
</script>



<style scoped>
@import '@/CSS/HomePage.css';

.ranking-card {
  flex: 1;
  background: white;
  border-radius: 12px;
  padding: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  text-align: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  position: relative;
  overflow: hidden;
}

.ranking-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.ranking-card.hot-sale {
  background: linear-gradient(135deg, #fff1f0 0%, #fff 100%);
  border: 1px solid #ffccc7;
}

.ranking-card.good-reputation {
  background: linear-gradient(135deg, #fff7e6 0%, #fff 100%);
  border: 1px solid #ffe7ba;
}

.ranking-card.good-price {
  background: linear-gradient(135deg, #f6ffed 0%, #fff 100%);
  border: 1px solid #d9f7be;
}

.card-icon {
  font-size: 24px;
  margin-bottom: 8px;
}

.card-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 4px;
}

.card-desc {
  font-size: 12px;
  color: #666;
}

.hot-sale .card-title { color: #cf1322; }
.good-reputation .card-title { color: #d46b08; }
.good-price .card-title { color: #389e0d; }
</style>
